#!/usr/bin/env python3
# -*- coding:utf-8 -*-
## author : cypro666
## date   : 2014.8.30
"""
Utils for running system commands(always on unix/linux os)
"""
import time, sys
from subprocess import Popen, PIPE

__all__ = ['SysCommand']


class SysCommand(object):
    """If using this class, know what you do very clearly anytime!"""
    @staticmethod
    def execute(cmd, show = False):
        output = Popen(cmd, shell=True, stdout=PIPE)
        if show:
            sys.stdout.write(cmd+'\n')
        return str(output.stdout.read(), 'utf-8')
    
    @staticmethod
    def count_process(keyword, show = False):
        output = Popen('ps ax | egrep %s' % keyword, shell=True, stdout=PIPE)
        lines = []
        for line in output.stdout:
            line = str(line, 'utf-8')
            if keyword in line and 'grep ' not in line:
                lines.append(line)
        return len(lines), tuple(lines)
        
    @staticmethod
    def count_process_ex(keyword, exclude, show = False):
        output = Popen('ps ax | egrep %s' % keyword, shell=True, stdout=PIPE)
        lines = []
        for line in output.stdout:
            line = str(line, 'utf-8')
            if keyword in line and exclude not in line and 'grep ' not in line:
                lines.append(line)
        return len(lines), tuple(lines)
    
    @staticmethod
    def getpid(keyword, show = False):
        output = Popen('ps ax | egrep %s' % keyword, shell=True, stdout=PIPE)
        pp = {}
        for line in output.stdout:
            line = str(line, 'utf-8')
            if keyword in line and 'grep ' not in line:
                pid = line.strip().split()[0]
                pp[pid] = line
        return pp


def test():
    r = SysCommand.execute('ls -al')
    print(r)
    
    n , r = SysCommand.count_process('python3')
    print(n)
    for item in r:
        print(item, end='')

    n, r = SysCommand.count_process_ex('python3', 'pydev')
    print(n)
    for item in r:
        print(item, end='')

    print(SysCommand.getpid('syscommand.py'))
    
    for i in range(5):
        print(SysCommand.execute('uptime'), end="")
        print(SysCommand.execute('free -mo'))
        time.sleep(1.0)

if __name__ == '__main__':
    test() 


